package com.yangyouli.unity_demo_server.util;

import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.sun.mail.util.MailSSLSocketFactory;

public class EmailUtil {
	// 存储邮件配置文件的路径节点所在 xml 中的配置路径
	private static final String NODE_PATH = "/container/email-conf-path";
	private static final String PROTOCAL;
	private static final String DOMAIN;
	private static final String MAIL_HOST;
	private static final String EMAIL_ACCOUNT;
	private static final String EMAIL_PWD;
	
	private static Properties prop = new Properties();
	private static MailSSLSocketFactory sf;
	private static Logger log = Logger.getLogger(EmailUtil.class);
	
	static {
		// 初始化
		// 得到 ContainerConfig.xml 配置文件的路径
		String configPath = PropertiesHelper.getPropertiesValue("ContainerConfig");
		
		Map<String, List<String>> confPath = ReadStringXml.getNodesValues(configPath, new String[] { NODE_PATH });
		Map<String, String> valueMap = PropertiesHelper.getPropertiesValueMap(confPath.get(NODE_PATH).get(0));
		
		PROTOCAL = valueMap.get("protocal");
		DOMAIN = valueMap.get("domain");
		MAIL_HOST = PROTOCAL + "." + DOMAIN;
		EMAIL_ACCOUNT = valueMap.get("account");
		EMAIL_PWD = valueMap.get("password");
		
		try {
			sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			prop.put("mail.smtp.ssl.enable", true);
			prop.put("mail.smtp.ssl.socketFactory", sf);
		} catch (GeneralSecurityException e) {
			log.error("创建 MailSSLSocketFactory 对象发生异常", e);
		}
		prop.setProperty("mail.host", MAIL_HOST);
        prop.setProperty("mail.transport.protocol", PROTOCAL);
        prop.setProperty("mail.smtp.auth", "true");
	}
	
	/**
	 * 发送邮件
	 * @param emailAddress 邮箱地址
	 * @param title 标题
	 * @param content 内容
	 */
    public static void sendMail (String emailAddress, String title, String content) {
        // 使用JavaMail发送邮件的5个步骤
        // 1、创建session
        Session session = Session.getInstance(prop);
        // 2、通过session得到transport对象
        Transport ts;
		try {
			ts = session.getTransport();
	        // 3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和第三方登陆码（不是密码）给smtp服务器，
	        // 用户名和密码都通过验证之后才能够正常发送邮件给收件人。
	        ts.connect(MAIL_HOST, EMAIL_ACCOUNT, EMAIL_PWD);
	        // 4、创建邮件
	        Message message = createSimpleMail(session, emailAddress, title, content);
	        // 5、发送邮件
	        ts.sendMessage(message, message.getAllRecipients());
	        ts.close();
		} catch (Exception e) {
			log.error("发送标题为[" + title + "]的邮件给[" + emailAddress + "]时发生异常", e);
		}
    }
    
    /**
    * @Method: createSimpleMail
    * @Description: 创建一封只包含文本的邮件
    * @Anthor:孤傲苍狼
    *
    * @param session
    * @return
    * @throws Exception
    */ 
    static MimeMessage createSimpleMail(Session session, String sendToEmailAddress, String title, String content)
            throws Exception {
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(EMAIL_ACCOUNT + "@" + DOMAIN));
        //指明邮件的收件人，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(sendToEmailAddress));
        //邮件的标题
        message.setSubject(title);
        //邮件的文本内容
        message.setContent(content, "text/html;charset=UTF-8");
        //返回创建好的邮件对象
        return message;
    }
}
